<template>
  <el-dialog
    :model-value="visible"
    title="加入班级"
    width="500px"
    @close="handleClose"
    @update:model-value="$emit('update:visible', $event)"
  >
    <div class="space-y-6">
      <!-- 班级ID输入 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">班级ID</label>
        <el-input
          v-model="joinForm.classId"
          placeholder="请输入班级ID"
          class="w-full"
          :prefix-icon="Document"
          clearable
        />
        <p class="text-xs text-gray-500 mt-1">班级ID通常由班主任或管理员提供</p>
      </div>

      <!-- 申请理由 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">申请理由</label>
        <el-input
          v-model="joinForm.reason"
          type="textarea"
          :rows="4"
          placeholder="请简要说明申请加入该班级的理由（可选）"
          class="w-full"
          maxlength="200"
          show-word-limit
        />
      </div>

      <!-- 班级信息预览 -->
      <div v-if="classInfo" class="bg-gray-50 rounded-lg p-4">
        <h4 class="font-medium text-gray-900 mb-3">班级信息</h4>
        <div class="grid grid-cols-2 gap-4 text-sm">
          <div>
            <span class="text-gray-600">班级名称：</span>
            <span class="text-gray-900">{{ classInfo.className }}</span>
          </div>
          <div>
            <span class="text-gray-600">年级：</span>
            <span class="text-gray-900">{{ classInfo.grade }}</span>
          </div>
          <div>
            <span class="text-gray-600">班主任：</span>
            <span class="text-gray-900">{{ classInfo.teacherName }}</span>
          </div>
          <div>
            <span class="text-gray-600">学生数量：</span>
            <span class="text-gray-900">{{ classInfo.studentCount }}</span>
          </div>
        </div>
        <div v-if="classInfo.description" class="mt-3">
          <span class="text-gray-600">班级描述：</span>
          <p class="text-gray-900 text-sm mt-1">{{ classInfo.description }}</p>
        </div>
      </div>

      <!-- 错误提示 -->
      <div v-if="errorMessage" class="bg-red-50 border border-red-200 rounded-lg p-3">
        <div class="flex items-center gap-2 text-red-800">
          <el-icon><Warning /></el-icon>
          <span class="text-sm">{{ errorMessage }}</span>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-end gap-3">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleJoin" 
          :loading="joining"
          :disabled="!canJoin"
        >
          申请加入
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Document, 
  Warning 
} from '@element-plus/icons-vue'
import { joinClass, getClassDetail } from '@/api/class'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const joining = ref(false)
const errorMessage = ref('')
const classInfo = ref(null)

// 表单数据
const joinForm = reactive({
  classId: '',
  reason: ''
})

// 计算属性
const canJoin = computed(() => {
  return joinForm.classId.trim() !== ''
})

// 监听器
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 弹窗打开时重置表单
    resetForm()
  }
})

// 方法
const resetForm = () => {
  Object.assign(joinForm, {
    classId: '',
    reason: ''
  })
  errorMessage.value = ''
  classInfo.value = null
}

const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

const validateClass = async () => {
  // 由于新的API接口会直接处理验证，这里可以简化或移除验证逻辑
  // 如果需要显示班级信息预览，可以在这里添加相应的逻辑
  return true
}

const handleJoin = async () => {
  if (!canJoin.value) return
  
  try {
    joining.value = true
    errorMessage.value = ''
    
    // 提交加入申请
    const joinData = {
      method: 'classId',
      classId: joinForm.classId,
      reason: joinForm.reason.trim() || undefined
    }
    
    const result = await joinClass(joinData)
    console.log(result.data);
    if (result.success) {
      // 通过班级ID申请加入 - 显示申请成功，更新待审核申请
      ElMessage.success('申请提交成功，请等待班主任审核')
      emit('success', { 
        type: 'application', 
        data: result.data,
        incrementPending: true  // 标记需要增加待审核申请数
      })
      handleClose()
    } else {
      // 显示具体的错误信息
      errorMessage.value = result.message || '申请提交失败，请重试'
    }
    
  } catch (error) {
    if (error.response?.data?.message) {
      errorMessage.value = error.response.data.message
    } else {
      errorMessage.value = '申请提交失败，请重试'
    }
  } finally {
    joining.value = false
  }
}
</script>

<style scoped>
/* 自定义样式 */
</style>
